package com.yanxi.filter;

import com.yanxi.utils.CurrentHolder;
import com.yanxi.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    public static final Logger log = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取请求路径
        String requestURI =request.getRequestURI();

        //2.判断是否为登录请求
        if(requestURI.contains("/login")){
            log.info("登录操作,放行");
            filterChain.doFilter(request,response);
            return;
        }

        //3.获取请求头token
        String token = request.getHeader("token");

        //4.判断token是否为空,如果为空,则返回错误结果
        if(token == null || token.isEmpty()){
            log.info("请求头token为空,返回错误结果");
            response.setStatus(401);
            return;
        }

        //5.不是空,则解析token,失败则返回错误结果,成功则放行
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer empId = (Integer) claims.get("id");
            CurrentHolder.setCurrentId(empId);
            log.info("当前用户id为:{} 将其存入ThreadLocal",empId);
        } catch (Exception e) {
            log.info("解析令牌失败,返回错误结果");
            response.setStatus(401);
            return;
        }

        //6.放行
        log.info("令牌合法,放行");
        filterChain.doFilter(request,response);

        //7.清除ThreadLocal中的用户id
        CurrentHolder.remove();
    }

}
